package com.ctg.itrdc.sysmgr.permission.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

public class BeanPropertiesMapper {

	public static <T> T rowmap2DTO(Class<T> dtoClass, Map<String, Object> rowMap) {
		T dto = null;
		try {
			dto = dtoClass.newInstance();
			Field[] fds = dtoClass.getDeclaredFields();
			Object value;
			try {
				for (String str : rowMap.keySet()) {
					for (Field f : fds) {
						if (str.replaceAll("_", "").equalsIgnoreCase(f.getName())) {
							value = rowMap.get(str);
							if(value instanceof List) {
								List l = (List)value;
								List<T> dtoList = mapList2DTOList(dtoClass, l);
								BeanUtils.setProperty(dto, f.getName(), dtoList);
							} else {
								BeanUtils.setProperty(dto, f.getName(), value);
							}
						}
					}
				}
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return dto;
	}

	public static <T> List<T> mapList2DTOList(Class<T> dtoClass,
			List<Map<String, Object>> list) {
		if(list == null || list.size() == 0) return null;
		List<T> res = new ArrayList<T>();
		for (Map<String, Object> map : list) {
			T t = rowmap2DTO(dtoClass, map);
			res.add(t);
		}
		return res;
	}
}
